<template>
  <div class="onedb-container">
    <div class="button-container">
      <el-button type="primary" icon="el-icon-back" @click="gotomain">返回</el-button>
    </div>
    <br><br>
    <!-- 显示属性集 -->
    <div class="attributes">
      {{ filteredAtAttributes }}
    </div>
    <!-- 显示函数依赖 -->
    <div class="dependencies">
      {{ functionDependencies }}
    </div>
    <!-- 数据库名称 -->
    <div class="section-title">
      <h2>{{ dbData.dbname }}</h2>
    </div>
    
    <!-- 展示属性集与对应的元组数据 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column v-for="(attribute, index) in filteredAtAttributesArray" :key="index" :label="attribute.value">
        <template slot-scope="scope">
          {{ scope.row[attribute.key.replace('u', 't')] }}

        </template>
      </el-table-column>
      
    </el-table>
    <br>

  
    <el-button type="primary" @click="showDatabaseInput">新建一致子实例</el-button>

 <!-- 元组输入表格 -->
 <el-table v-if="databaseName && filteredAtAttributesArray.length > 0" :data="tuples" style="width: 100%">
      <el-table-column v-for="(attribute, index) in filteredAtAttributesArray" :key="index" :label="attribute.value">
        <template slot-scope="scope">
          <el-input v-model="scope.row[attribute.value]"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="removeTuple(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-button v-if="databaseName && filteredAtAttributesArray.length > 0" type="primary" @click="addTuple">添加元组</el-button>
    <el-button v-if="databaseName && filteredAtAttributesArray.length > 0" type="primary" @click="sendTuple">保存数据库</el-button>
 
    
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { selectdb,createcondb } from '@/api/db';
import { dbtps,deleteTp,addonetp,addtp } from '@/api/dbt';
import { MessageBox } from 'element-ui';

export default {
  name: 'onedb',
  created() {
    this.read();
  },
  computed: {
    ...mapGetters([
      'token', 
      'DBid'
    ]),

    filteredAtAttributes() {
      const attributes = [];
      for (let key in this.dbData.at) {
        if (this.dbData.at.hasOwnProperty(key) && key >= 'ua' && key <= 'um' && this.dbData.at[key] !== null && key != 'uid') {
          attributes.push(`${this.dbData.at[key]}`);
        }
      }
      return attributes.length > 0 ? `属性集: ${attributes.join(', ')}` : '';
    },
    filteredAtAttributesArray() {
      const attributes = [];
      for (let key in this.dbData.at) {
        if (this.dbData.at.hasOwnProperty(key) && key >= 'ua' && key <= 'um' && this.dbData.at[key] !== null && key != 'uid') {
          attributes.push({ key, value: this.dbData.at[key] });
        }
      }
      return attributes;
    },
    functionDependencies() {
      const dependencies = [];
      for (let key in this.dbData.fd) {
        if (this.dbData.fd.hasOwnProperty(key)) {
          if (key.endsWith('l') && this.dbData.fd[key] !== null) {
            const rightKey = key.replace('l', 'r');
            if (this.dbData.fd[rightKey] !== null) {
              dependencies.push(`${this.dbData.fd[key]} -> ${this.dbData.fd[rightKey]}`);
            }
          }
        }
      }
      return dependencies.length > 0 ? `函数依赖集: ${dependencies.join(', ')}` : '';
    },
    tableData() {
      return this.tpData.map(tuple => {
        const row = {};
        this.filteredAtAttributesArray.forEach(attr => {
          const tupleKey = attr.key.replace('u', 't');
          row[tupleKey] = tuple[tupleKey];
        });
        row.tid = tuple.tid;
        return row;
      });
    },
  },
  data() {
    return {
      dbData: {},
      tpData: [],
      keyword: '',
      showDialog: false,
      newDatabaseName: '',
      databaseName: '',
      tuples: [],
      newdbid: '',
      rtuples: [],
      num: 0,
      dialogVisible: false, // 控制对话框的显示状态
      newTuple: {} // 新元组的数据
    };
  },
  methods: {
    read() {
      selectdb(this.DBid).then(response => {
        this.dbData = response.data.db;
        console.log(this.dbData)
        console.log("dbData")
      }).catch(error => console.log(error));

      dbtps(this.DBid).then(response => {
        this.tpData = response.data.tp;
        console.log(this.tpData)
        console.log("tpData")
      }).catch(error => console.log(error));
    },
    gotomain() {
      this.$router.go(-1); // 返回上一页
    },
    showDatabaseInput() {
      this.createDatabase();
    },
    createDatabase() {
    const newDatabaseName = `${this.dbData.dbname} 子集修复`;
    //此处不需要用户自行取名，直接用子集修复命名
    if (newDatabaseName.trim()) {
      this.databaseName = newDatabaseName;
      createcondb(this.DBid, this.databaseName).then(response => {
        this.newdbid = response.data.dbid;
        this.addTuple(); // 初始化时添加一个空元组
      }).catch(error => {
        console.log(error);
      });
    } else {
      this.$message.error('数据库名称生成失败');
    }
  },
    addTuple() {
      if (!this.filteredAtAttributesArray || this.filteredAtAttributesArray.length === 0) {
        console.error('filteredAtAttributesArray is not properly initialized');
        return;
      }

      const tuple = {};
      this.filteredAtAttributesArray.forEach(attribute => {
        tuple[attribute.value] = ''; // 使用属性值作为键
      });
     
      this.tuples.push(tuple);
      this.num++; // 增加计数器
      console.log(this.tuples[0])
      //addtp(this.tuples)
      
    },
    removeTuple(index) {
      this.tuples.splice(index, 1);
    },
    sendTuple() {//数据库元组传输到后端
      this.rtuples = [];
      // 遍历每个 tuple
      this.tuples.forEach(tuple => {
        const rtuple = {
          dbid: this.newdbid,
          ta: null,
          tb: null,
          tc: null,
          td: null,
          te: null,
          tf: null,
          tg: null,
          th: null,
          ti: null,
          tj: null,
          tk: null,
          tl: null,
          tn: null,
          tm: null
        };

        // 根据 filteredAtAttributesArray 的顺序赋值
        this.filteredAtAttributesArray.forEach((attribute, index) => {
          const attributeValue = tuple[attribute.value];
          if (attributeValue !== undefined && attributeValue !== '') {
            rtuple[`t${String.fromCharCode(97 + index)}`] = attributeValue; // a=97 in ASCII
          }
        });

        // 将生成的 rtuple 添加到 rtuples 数组中
        this.rtuples.push(rtuple);
      });
      console.log(this.num)
      console.log("看看计数器")

      console.log(this.rtuples); // 输出结果
      addtp(this.rtuples).then(response => {
        this.$message({
          message: '新建数据库成功',
          type: 'success'
        })
        setTimeout(() => {
      //this.$router.push('/DBII/alldb');
      console.log("月光月光浩茫茫")
      this.$store.dispatch('user/setDBId', this.DBid)
          .then(() => this.$store.dispatch('user/setNEWDBID', this.newdbid))
          .then(() => {
            this.$router.push('/CHECK/repair_checking');
          })
    }, 1000); // 3000 毫秒 = 3 秒
            }).catch(error => {
                console.log(error);
            })

    }
    
  }
};
</script>

<style lang="scss" scoped>
.onedb {
  &-container {
    margin: 30px;
    font-family: Arial, sans-serif;
  }

  .tuple-form {
    margin-top: 20px;
  }
}

.section-title {
  margin: 20px 0;
  padding-bottom: 5px;
  border-bottom: 2px solid #ddd;
}

.attributes, .dependencies {
  margin-left: 20px;
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
}

.button-container {
  position: absolute;
  top: 20px; /* 距离顶部的距离 */
  right: 20px; /* 距离右边的距离 */
}
</style>